using System;
using System.Collections.Generic;
using Mall.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Mall.Api.ParamModel;
using Newtonsoft.Json;
using Mall.Api.Repository;
using Mall.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;

namespace Mall.Api.Controllers
{
    /// <summary>
    /// 立即购买和加入购物车
    /// </summary>
     [Authorize]
    [ApiController]
    [Route("buyjoinshoppingcart")]
    public class BuyController : ControllerBase
    {




        private IRepository<CommodityProperty> _commodityProperty;
        private IRepository<CommodityPropertyValue> _commodityPropertyValue;
        private IRepository<CommoditySKU> _commoditySKU;
        private IRepository<Commodity> _commodity;
        private IRepository<Users> _usersRespository;
        private IRepository<Payment> _payment;
        private IRepository<OrderStatu> _orderStatu;
        private IRepository<UserOrder> _userOrder;
        private IRepository<Order> _order;
        private IRepository<ShoppingCart> _shoppingCart;
        private IRepository<UserShoppingTrolley> _userShoppingTrolley;

        private readonly IConfiguration _configuration;

        public BuyController(IConfiguration configuration,
       IRepository<CommodityProperty> commodityProperty, IRepository<CommodityPropertyValue> commodityPropertyValue,
        IRepository<CommoditySKU> commoditySKU, IRepository<Commodity> commodity,
        IRepository<Supplier> supplier, IRepository<Users> usersRespository, IRepository<Payment> payment, IRepository<OrderStatu> orderStatu,
        IRepository<UserOrder> userOrder, IRepository<Order> order, IRepository<UserShoppingTrolley> userShoppingTrolley, IRepository<ShoppingCart> shoppingCart)
        {
            _configuration = configuration;
            _commodityProperty = commodityProperty;
            _commodityPropertyValue = commodityPropertyValue;
            _commoditySKU = commoditySKU;
            _commodity = commodity;
            _usersRespository = usersRespository;
            _payment = payment;
            _orderStatu = orderStatu;
            _userOrder = userOrder;
            _order = order;
            _userShoppingTrolley = userShoppingTrolley;
            _shoppingCart = shoppingCart;


        }


        /// <summary>
        /// 立即购买
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public dynamic Post(BuyCommodity model)
        {


            // var buyInfo = (from commoditySKU in _commoditySKU.Table
            //                join commodityProperty in _commodityProperty.Table on commoditySKU.CommodityPropertyId equals commodityProperty.Id
            //                join commodityPropertyValue in _commodityPropertyValue.Table on commoditySKU.CommodityPropertyValueId equals commodityPropertyValue.Id
            //                join commodity in _commodity.Table on commoditySKU.CommodityId equals commodity.Id
            //                where commoditySKU.IsActived == true
            //                select new
            //                {

            //                    CommodityId = commoditySKU.CommodityId,
            //                    CommodityPropertyId = commoditySKU.CommodityPropertyId,
            //                    CommodityPropertyValueId = commoditySKU.CommodityPropertyValueId
            //                }).ToList();

            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;


            var balance = _usersRespository.Table.Where(b => b.Id == int.Parse(userid)).FirstOrDefault().Balance;


            Random rd = new Random();//用于生成随机数
            string DateStr = DateTime.Now.ToString("yyyyMMddHHmmssMM");//日期
            string str = DateStr + rd.Next(10000).ToString().PadLeft(4, '0');//带日期的随机数

            var orderCode = str;
            var uid = userid;
            var paymentName = model.PaymentName;
            var parmentId = _payment.Table.Where(pt => pt.PaymentName == paymentName).FirstOrDefault().Id;
            var count = model.Count;
            var price = model.Price;
            if (balance < price)
            {

                var tmps = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "余额不足！"
                };
                return JsonHelper.Serialize(tmps);
            }
            var usod = _userOrder.Table.Where(u => u.UsersId == int.Parse(userid)).FirstOrDefault();

                var userOrder = new UserOrder
                {
                    Users = _usersRespository.Table.Single(u => u.Id == int.Parse(userid)),
                    Payment = _payment.Table.Single(p => p.Id == parmentId),
                    OrderStatu = _orderStatu.Table.Single(o => o.Id == 1),
                    Number = count,
                    OrderCode = orderCode,
                    Total = price

                };


                _userOrder.Insert(userOrder);
                usod = userOrder;
            


            var ord = new List<Order>();
            foreach (var item in model.SKU)
            {
                var oneSku = _commoditySKU.Table.Single(c => c.CommodityPropertyId == item[0] && c.CommodityPropertyValueId == item[1]);
                // var skus = _commoditySKU.Table.Where(s => s.CommodityPropertyId == item.CommodityPropertyId && s.CommodityPropertyValueId == s.CommodityPropertyValueId).FirstOrDefault().Id;
                var order = new Order
                {

                    CommoditySKU = oneSku,
                    UserOrder = usod
                };
                ord.Add(order);
            }
        _order.InsertBulkAsync(ord);


            var tmp = new
            {
                Code = 200,
                Data = ord,
                Msg = "生成订单成功！"
            };
            return JsonHelper.Serialize(tmp);

        }






        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("shoppingcart")]
        public dynamic PostCart(BuyCommodity model)
        {


            // var buyInfo = (from commoditySKU in _commoditySKU.Table
            //                join commodityProperty in _commodityProperty.Table on commoditySKU.CommodityPropertyId equals commodityProperty.Id
            //                join commodityPropertyValue in _commodityPropertyValue.Table on commoditySKU.CommodityPropertyValueId equals commodityPropertyValue.Id
            //                join commodity in _commodity.Table on commoditySKU.CommodityId equals commodity.Id
            //                where commoditySKU.IsActived == true&&model.CommodityId==commoditySKU.CommodityId
            //                select new
            //                {

            //                    CommodityId = commoditySKU.CommodityId,
            //                    CommodityPropertyId = commoditySKU.CommodityPropertyId,
            //                    CommodityPropertyValueId = commoditySKU.CommodityPropertyValueId
            //                }).ToList();

            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;

            var ust = _userShoppingTrolley.Table.Where(u => u.UsersId == int.Parse(userid)).FirstOrDefault();

            if (ust == null)
            {
                var uid = new UserShoppingTrolley
                {
                    Users = _usersRespository.Table.Single(u => u.Id == int.Parse(userid))
                };

                _userShoppingTrolley.Insert(uid);
                ust = uid;
            }



            var shopping = new List<ShoppingCart>();
            foreach (var item in model.SKU)
            {
                // var skus = _commoditySKU.Table.Where(s => s.CommodityPropertyId == item.CommodityPropertyId && s.CommodityPropertyValueId == s.CommodityPropertyValueId).FirstOrDefault().Id;
                var oneSku = _commoditySKU.Table.Single(c => c.CommodityPropertyId == item[0] && c.CommodityPropertyValueId == item[1]);
                // var ccc = _userShoppingTrolley.Table.Single(u => u.Id == ust.UsersId);

                var shoppingCart = new ShoppingCart
                {

                    CommoditySKU = oneSku,
                    UserShoppingTrolley = ust
                };
                shopping.Add(shoppingCart);

            }

            _shoppingCart.InsertBulk(shopping);

            var tmp = new
            {
                Code = 200,
                Data = shopping,
                Msg = "加入购物车成功！"
            };
            return JsonHelper.Serialize(tmp);

        }






    }


}
